package com.zyfdroid.bigdialerkit.services;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.provider.CallLog;
import android.text.TextUtils;
import android.widget.AdapterView;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import com.zyfdroid.bigdialerkit.MissedCallDetailActivity;
import com.zyfdroid.bigdialerkit.R;
import com.zyfdroid.bigdialerkit.dao.MissingCall;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class MissedCallsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {

    Context mContext;

    List<MissingCall> missingCallList;

    public MissedCallsRemoteViewsFactory(Context ctx) {
        this.mContext = ctx;
        missingCallList = new ArrayList<>();
    }

    @Override
    public void onCreate() {
        onDataSetChanged();
    }

    @Override
    public void onDataSetChanged() {
        missingCallList = MissingCall.LoadData(mContext);
    }

    @Override
    public void onDestroy() {
        missingCallList = null;
    }

    @Override
    public int getCount() {
        return missingCallList.size();
    }

    @Override
    public RemoteViews getViewAt(int position) {
        if (position == AdapterView.INVALID_POSITION ||
                missingCallList == null || position >= missingCallList.size()) {
            return null;
        }
        MissingCall item = getItemAt(position);
        RemoteViews rvs = new RemoteViews(mContext.getPackageName(),R.layout.adapter_missed_calls);
        rvs.setTextViewText(R.id.txtMissingCallContactName,item.displayName);
        rvs.setTextViewText(R.id.txtMissingCallContactTime,FormatDateDiff(System.currentTimeMillis(),item.callTime)+"打过");


        // 创建Intent，并附加MissingCall对象的数据
        Intent intent = new Intent();
        intent.putExtra("_id", item._id);
        intent.putExtra("displayName", item.displayName);
        intent.putExtra("phoneNumber", item.phoneNumber);
        intent.putExtra("callTime", item.callTime);
        // 设置PendingIntent，当点击列表项时填充Intent
        rvs.setOnClickFillInIntent(R.id.listMissingCallsItem, intent);
        return rvs;
    }

    @Override
    public RemoteViews getLoadingView() {
        return new RemoteViews(mContext.getPackageName(), R.layout.adapter_missed_calls_loading);
    }

    private MissingCall getItemAt(int position){
        return missingCallList.get(position);
    }



    public static String FormatDateDiff(long now, long target) {
        if (target > now) {
            return "将来";
        }

        long diff = now - target;
        long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
        long hours = TimeUnit.MILLISECONDS.toHours(diff + 29*60*1000);

        long days = 0;
        {
            long dateEpoch = new Date(2000,11,20).getTime();
            long nowDateStamp = (now - dateEpoch) / 86400000;
            long diffStamp = (target - dateEpoch) / 86400000;
            days = nowDateStamp - diffStamp;
        }


        if (days > 7) {
            return "很久以前";
        } else if (minutes < 20) {
            return "刚才";
        } else if (minutes < 40) {
            return "半小时前";
        } else if (hours < 4) {
            return hours + "小时前";
        } else {
            java.util.Calendar calendar = java.util.Calendar.getInstance();
            calendar.setTimeInMillis(target);
            int hour = calendar.get(java.util.Calendar.HOUR_OF_DAY);
            int hourCasual = hour > 12 ? hour - 12 : (hour == 0 ? 12 : hour);
            int dayOfWeek = calendar.get(java.util.Calendar.DAY_OF_WEEK);
            calendar.setTimeInMillis(now);
            int dayOfWeekNow = calendar.get(java.util.Calendar.DAY_OF_WEEK);


            String timeOfDay;
            if (hour < 3) {
                timeOfDay = "半夜" + hourCasual + "点";
            } else if (hour < 5) {
                timeOfDay = "凌晨" + hourCasual + "点";
            } else if (hour <= 8) {
                timeOfDay = "早上" + hourCasual + "点";
            } else if (hour <= 11) {
                timeOfDay = "上午" + hourCasual + "点";
            } else if (hour == 12) {
                timeOfDay = "中午" + hourCasual + "点";
            } else if (hour < 17) {
                timeOfDay = "下午" + hourCasual + "点";
            } else if (hour < 19) {
                timeOfDay = "傍晚" + hourCasual + "点";
            } else {
                timeOfDay = "晚上" + hourCasual + "点";
            }
            boolean hasLast = dayOfWeek > dayOfWeekNow;
            String lastPrefix = hasLast ? "上" : "";
            if (days == 0) {
                return timeOfDay;
            } else if (days == 1) {
                if (hour < 2) {
                    return "前天半夜" + hourCasual + "点";
                } else {
                    return "昨天" + timeOfDay;
                }
            } else if (days == 2) {
                if (hour < 2) {
                    String[] weekdays = {"", "周日", "周一", "周二", "周三", "周四", "周五", "周六"};
                    return hasLast ? "上"+weekdays[dayOfWeek] : weekdays[dayOfWeek]+timeOfDay;
                } else {
                    return "前天" + timeOfDay;
                }
            } else {
                String[] weekdays = {"", "周日", "周一", "周二", "周三", "周四", "周五", "周六"};
                return hasLast ? "上"+weekdays[dayOfWeek] : weekdays[dayOfWeek]+timeOfDay;
            }
        }
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @Override
    public long getItemId(int position) {
        return getItemAt(position)._id;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }
}
